/* Copyright (c) 2009-2010, Sean A.O. Harney <sharney3@gmail.com> */

#include "omf.h"


#define EMAIL_COMMAND_STR "/usr/lib/sendmail"


void mail_alert(char *dirname, char *msg)
{
    uint8_t *mem;
    int fd;
    struct stat st;
    FILE *fp;
    char boundary[33];		//32char and a \0
    char zip_file[255];
    return;
    /* 
       TODO: reply-to: 
       we can let the mail program add the To: as its doing per recipeint
     */

#define ALERT_TMP "/tmp/sdsf"
    if ((fp = fopen(ALERT_TMP, "w+")) == NULL)
      {
	  //KMTLog_err("fopen() failed upon opening message to Notify Users\n");
	  return;
      }

    srand(time(NULL));
    for (i = 0; i < 32; i++)
      {
	  do
	    {
		r = (rand() % 126) + '0';
	    }
	  while (!isalnum(r));	//keep trying till we get an alnum

	  boundary[i] = r;
      }
    boundary[32] = '\0';

    fprintf(fp, "Subject: %s\n" "MIME-Version: 1.0\n" "Content-Type: multipart/mixed; boundary=\"%s\"\n\n"	// \\n\n seperates heder from email body
	    , "KMT ALERT", boundary);



    if ((fd = open(zip_file, O_RDONLY)) < 0)
      {
	  fprintf(stderr,
		  "Unable to open zip file %s for alert attachment: %s\n",
		  zip_file, strerror(errno));
	  goto skip_attachment;
      }

    if (fstat(fd, &st) < 0)
      {

	  fprintf(stderr,
		  "Unable to stat zip file %s for alert attachment: %s\n",
		  zip_file, strerror(errno));
	  goto skip_attachment;
      }

    mem = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
    if (mem == MAP_FAILED)
      {
	  fprintf(stderr,
		  "Unable to mmap zip file %s for alert attachment: %s\n",
		  zip_file, strerror(errno));
	  goto skip_attachment;
      }



    int outz = st.st_size * 2.5 + 10;	// a little bigger than the biggest possible b64 encoding.
    char *out = checked_malloc(outz);

    if (base64_encode(mem, st.st_size, out, outz) == 0)	//failed
      {
	  free(out);
	  //KMTLog_err("base64_encode() failed\n");
	  goto skip_attachment;
      }

    char *fname = strrchr(zip_file, '/');
    if (fname == NULL)		// was not an absolute path
	fname = zip_file;
    else
	fname++;		//fname now points to the file name


    fprintf(fp,
	    "--%s\n"
	    "Content-Type: application/zip\n"
	    "Content-Disposition: attachment; filename=\"%s\"\n"
	    "Content-Transfer-Encoding: base64\n\n", boundary, fname);



// must be under 998 octets
#define MIME_LINELEN 60
    //TODO: make this write in chunks for efficiency
    for (i = 0; out[i] != '\0'; i++)
      {
	  fwrite(&out[i], 1, 1, fp);
	  if (i % MIME_LINELEN == MIME_LINELEN - 1)	// smtp requires a enwline after at most 998 octets
	      fprintf(fp, "\n");
      }

    fprintf(fp, "\n--%s--\n", boundary);
    fflush(fp);
    fclose(fp);
    free(out);
    //NotifyUsers(NULL);
    return;

  skip_attachment:

    fflush(fp);
    fclose(fp);
    if (out != NULL)
	free(out);
    //NotifyUsers(NULL);
    munmap(mem, st.st_size);

}
